package scatter.interview.rest.interview.i2_sort;

/**
 * 插入排序
 * Created by yangwei
 * Created at 2021/4/9 13:52
 */
public class InsertionSort implements ICompareSort<int[]>{

    /**
     * 插入排序
     * @param array
     * @return
     */
    public static int[] insertionSort(int[] array) {
        if (array.length == 0){
            return array;
        }

        int current;
        for (int i = 0; i < array.length - 1; i++) {
            current = array[i + 1];
            int preIndex = i;
            while (preIndex >= 0 && current < array[preIndex]) {
                array[preIndex + 1] = array[preIndex];
                preIndex--;
            }
            array[preIndex + 1] = current;
        }
        return array;
    }
    @Override
    public int[] sort(int[] array) {
        insertionSort(array);
        return array;
    }


    public static void main(String[] args) {
        int[] arr = {10, 7, 2, 4, 7, 62, 3, 4, 2, 1,4, 2, 1,4, 2, 1, 8, 9, 19};
        new InsertionSort().sort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
